﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using LEEAAttendanceControl.Web.Services;
using BioStarCSharp;
using System.Runtime.InteropServices;
using System.Net;
using System.Threading;

using System.IO;
using System.Data.OleDb;
using System.Data;

namespace LEEAAttendanceControl.Web
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            IniateLog();
        }
        void IniateLog()
        {
            //Thread thread = new Thread(new ThreadStart(SaveLog));
            //thread.Start();
            //SaveLog();
            //ReadEmployees();
            //ReadEvents();
        }
        public void ReadEvents()
        {
            AttendanceDBEntities context = new AttendanceDBEntities();
            string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\172.16.3.2\atg\Events.mdb;Jet OLEDB:Database Password=atg@acs;";
            //string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\172.16.3.2\atg\Access_Control.mdb;Jet OLEDB:Database Password=atg@acs;";
            //string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\tmp\Access_Control.mdb;";
            OleDbConnection con = new OleDbConnection(constring);
            con.Open();
            foreach (Employee emp in context.Employees)
            {
                OleDbCommand cmd = new OleDbCommand("select Date,Time from Events where Data="+emp.CardNo.ToString() + " order by Date,time");
                cmd.Connection = con;
                IDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Attendance attendance = new Attendance();
                    attendance.EmployeeID = emp.EmployeeID;
                    attendance.DataTime=DateTime.Parse(DateTime.Parse(dr["Date"].ToString()).ToShortDateString()+" "+DateTime.Parse(dr["Time"].ToString()).ToShortTimeString());
                    context.Attendances.AddObject(attendance);
                    
                }
            }
            context.SaveChanges();
            con.Close();
        }

        public void ReadEmployees()
        {
              AttendanceDBEntities context = new AttendanceDBEntities();
 
            //string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\172.16.3.2\atg\Access_Control.mdb;Jet OLEDB:Database Password=atg@acs;";
            string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\tmp\Access_Control.mdb;";
            OleDbConnection con = new OleDbConnection(constring);
            con.Open();
            OleDbCommand cmd = new OleDbCommand("select * from personnel");
            cmd.Connection = con;
            IDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Employee emp = new Employee();
                int employeeid = 0, cardno=0;
                //if (dr["Employee_Number"] != null && int.TryParse(dr["Employee_Number"].ToString().Trim(), out employeeid) && int.TryParse(dr["Card_Number"].ToString().Trim(), out cardno))
                //{
                if (dr["Employee_Number"] != null && int.TryParse(dr["Employee_Number"].ToString().Trim(), out employeeid))
                    emp.EmployeeCode = employeeid;
                else
                    emp.EmployeeCode = null;
                emp.CardNo = int.Parse(dr["Card_Number"].ToString().Trim());
                emp.FirstName = dr["First_Name"].ToString();
                emp.LastName = dr["Last_Name"].ToString();
                emp.CompanyID = 1;
                emp.DepartmentID = 1;
                context.Employees.AddObject(emp);

                 
                //}
            }
            context.SaveChanges();
            con.Close();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        AttendanceDBEntities context = new AttendanceDBEntities();
        BSSDK.BSIPConfig m_ConfigBST;
        public const int MAX_DEVICE = 128;
        public const int TEMPLATE_SIZE = 384;

        public List<Device> GetDevices()
        {
            int m_Handle = -1;
            int m_NumOfDevice = 0;
            uint[] m_DeviceID;
            int[] m_DeviceType;
            uint[] m_DeviceAddr;

            m_DeviceID = new uint[MAX_DEVICE];
            m_DeviceType = new int[MAX_DEVICE];
            m_DeviceAddr = new uint[MAX_DEVICE];
            int result = BSSDK.BS_InitSDK();
            if (result == BSSDK.BS_SUCCESS)
            {
                result = BSSDK.BS_OpenInternalUDP(ref m_Handle);
                if (result == BSSDK.BS_SUCCESS)
                {
                    try
                    {
                        result = BSSDK.BS_SearchDeviceInLAN(m_Handle, ref m_NumOfDevice, m_DeviceID, m_DeviceType, m_DeviceAddr);
                        if (result == BSSDK.BS_SUCCESS)
                        {
                            List<Device> lstOfDevices = new List<Device>();
                            for (int i = 0; i < m_DeviceID.Length; i++)
                            {
                                if (m_DeviceID[i] != 0)
                                {
                                    Device d = new Device() { DeviceId = m_DeviceID[i].ToString(), Addr = m_DeviceAddr[i], Type = m_DeviceType[i], Handle = m_Handle };
                                    lstOfDevices.Add(d);
                                }
                            }
                            return lstOfDevices;

                        }
                    }
                    catch
                    {
                    }
                }
            }
            return null;
        }
        public List<LogRecord> ReadLog(uint deviceId)
        {
            int m_NumOfLog = 0;
            int handle = 0;
            int configSize = 0;
            List<LogRecord> lstOfRecords = new List<LogRecord>();

            try
            {
                List<Device> lstOfDevices = GetDevices();
                Device dev = (from d in lstOfDevices
                              where d.DeviceId == deviceId.ToString()
                              select d).FirstOrDefault();

                if (dev == null) return null;

                IntPtr config = Marshal.AllocHGlobal(Marshal.SizeOf(m_ConfigBST));
                int result = BSSDK.BS_ReadConfigUDP(dev.Handle, dev.Addr, deviceId, BSSDK.BS_CONFIG_TCPIP, ref configSize, config);
                if (result != BSSDK.BS_SUCCESS)
                {
                    Marshal.FreeHGlobal(config);
                    throw new Exception();
                }
                m_ConfigBST = (BSSDK.BSIPConfig)Marshal.PtrToStructure(config, typeof(BSSDK.BSIPConfig));
                Marshal.FreeHGlobal(config);
                uint port = 0;
                if (m_ConfigBST.useServer)
                {
                    port = m_ConfigBST.serverPort;
                }
                else
                {
                    port = m_ConfigBST.port;
                }
                IPAddress addr = new IPAddress(dev.Addr);
                result = BSSDK.BS_OpenSocket(addr.ToString(), (int)port, ref handle);
                ///////////////
                BSSDK.BS_GetLogCount(handle, ref m_NumOfLog);
                IntPtr lRecord = Marshal.AllocHGlobal(m_NumOfLog * Marshal.SizeOf(typeof(BSSDK.BSLogRecord)));
                int logTotalCount = 0;
                int logCount = 0;
                do
                {
                    IntPtr buf = new IntPtr(lRecord.ToInt32() + logTotalCount * Marshal.SizeOf(typeof(BSSDK.BSLogRecord)));
                    if (logTotalCount == 0)
                    {
                        result = BSSDK.BS_ReadLog(handle, 0, 0, ref logCount, buf);
                    }
                    else
                    {
                        result = BSSDK.BS_ReadNextLog(handle, 0, 0, ref logCount, buf);
                    }
                    if (result != BSSDK.BS_SUCCESS)
                    {
                        Marshal.FreeHGlobal(lRecord);
                        return null;
                    }

                    logTotalCount += logCount;

                } while (logCount == 8192);
                for (int i = 0; i < logTotalCount; i++)
                {
                    BSSDK.BSLogRecord record = (BSSDK.BSLogRecord)Marshal.PtrToStructure(new IntPtr(lRecord.ToInt32() + i * Marshal.SizeOf(typeof(BSSDK.BSLogRecord))), typeof(BSSDK.BSLogRecord));
                    if (record.eventType == 55 || record.eventType == 56)
                    {
                        LogRecord logrecord = new LogRecord();
                        logrecord.UserId = record.userID;
                        logrecord.EventTime = new DateTime(1970, 1, 1).AddSeconds(record.eventTime);
                        logrecord.EventType = record.eventType;
                        lstOfRecords.Add(logrecord);
                    }

                }
                Marshal.FreeHGlobal(lRecord);
                return lstOfRecords;
            }
            finally
            {
                BSSDK.BS_CloseSocket(handle);
            }
        }
        public void SaveLog()
        {
            while (true)
            {
                try
                {
                    foreach (Location loc in context.Locations)
                    {
                        List<LogRecord> lstOfLogRecords = ReadLog(uint.Parse("23475"));
                        if (lstOfLogRecords != null)
                        {
                            foreach (LogRecord lr in lstOfLogRecords)
                            {
                                Attendance attend = new Attendance();
                                attend.EmployeeID = (from e in context.Employees
                                                     where e.EmployeeCode == lr.UserId
                                                     select e.EmployeeID).FirstOrDefault();
                                attend.DataTime = lr.EventTime;
                                attend.ShiftID = (from s in context.ShiftAssignments
                                                  where s.EmployeeID == attend.EmployeeID && s.AssignmentFrom <= attend.DataTime && s.AssignmentTo >= attend.DataTime
                                                  select s.ShiftID).FirstOrDefault();
                                attend.Status = lr.EventType == 55 ? 1 : 0;
                                context.Attendances.AddObject(attend);
                            }
                        }
                    }
                    context.SaveChanges();
                }
                catch(Exception ex)
                {
                    using (StreamWriter writer = new StreamWriter(File.OpenWrite(@"C:\Error.txt")))
                    {
                        writer.WriteLine(ex.Message);
                    }
                    //throw new Exception();
                }
            }
        }


    }
}